<template>
  <div class="exam-paper-container">
    <!-- 试卷列表 -->
    <el-card v-if="showPaperList" shadow="hover" class="paper-list-card">
      <div slot="header" class="clearfix">
        <span>试卷列表</span>
      </div>
      <el-table
          :data="paperList"
          border
          style="width: 100%"
          @row-click="handlePaperClick"
      >
        <el-table-column
            prop="id"
            label="试卷ID"
            width="120"
        />
        <el-table-column
            prop="title"
            label="试卷标题"
        />
        <el-table-column
            prop="total_score"
            label="总分"
            width="100"
        />
        <el-table-column
            prop="pass_score"
            label="及格分"
            width="100"
        />
        <el-table-column
            prop="create_time"
            label="创建时间"
            width="180"
        />
      </el-table>
    </el-card>

    <!-- 试卷作答页面 -->
    <el-card v-else shadow="hover" class="paper-detail-card">
      <div slot="header" class="clearfix">
        <span>{{ currentPaper.title }}</span>
        <div class="timer-container">
          <span>剩余时间: {{ formatTime(remainingTime) }}</span>
        </div>
        <el-button
            type="primary"
            icon="el-icon-back"
            @click="showPaperList = true"
            style="float: right"
        >
          返回试卷列表
        </el-button>
      </div>

      <!-- 题目导航栏 -->
      <el-scrollbar class="question-nav">
        <el-row>
          <el-col
              :span="24/currentPaper.questions.length"
              v-for="(question, index) in currentPaper.questions"
              :key="question.id"
          >
            <el-button
                size="mini"
                :type="isAnswered(question.id) ? 'success' : 'primary'"
                @click="scrollToQuestion(index)"
            >
              {{ index + 1 }}
            </el-button>
          </el-col>
        </el-row>
      </el-scrollbar>

      <!-- 题目列表 -->
      <div
          class="question-item"
          v-for="(question, index) in currentPaper.questions"
          :key="question.id"
          :ref="'questionRef' + index"
      >
        <div class="question-title">
          {{ index + 1 }}. {{ question.content }}（分值：{{ question.score }} 分）
          <span class="question-type-tag">
            {{ getQuestionTypeName(question.type) }}
          </span>
        </div>

        <!-- 1. 单选题 -->
        <div v-if="question.type === 1" class="question-content">
          <el-radio-group v-model="userAnswers[question.id]">
            <el-radio
                v-for="(option, optIndex) in question.options"
                :key="optIndex"
                :label="option.key+':'+option.value"
            >
              {{ option.key }}: {{ option.value }}
            </el-radio>
          </el-radio-group>
        </div>

        <!-- 2. 多选题 -->
        <div v-if="question.type === 2" class="question-content">
          <el-checkbox-group v-model="userAnswers[question.id]">
            <el-checkbox
                v-for="(option, optIndex) in question.options"
                :key="optIndex"
                :label="option.value"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 3. 判断题 -->
        <div v-if="question.type === 3" class="question-content">
          <el-radio-group v-model="userAnswers[question.id]">
            <el-radio label="正确">正确</el-radio>
            <el-radio label="错误">错误</el-radio>
          </el-radio-group>
        </div>

        <!-- 4. 填空题 -->
        <div v-if="question.type === 4" class="question-content">
          <el-input
              v-model="userAnswers[question.id]"
              placeholder="请输入答案"
              clearable
          />
        </div>

        <!-- 5. 简答题 -->
        <div v-if="question.type === 5" class="question-content">
          <el-input
              type="textarea"
              :rows="5"
              v-model="userAnswers[question.id]"
              placeholder="请输入详细答案"
              autosize="{ minRows: 5, maxRows: 10 }"
          />
        </div>
      </div>

      <!-- 提交区域 -->
      <div class="submit-area">
        <el-button
            type="info"
            icon="el-icon-refresh"
            @click="resetAnswers"
        >
          重置答案
        </el-button>
        <el-button
            type="primary"
            icon="el-icon-arrow-left"
            @click="prevQuestion"
            :disabled="currentQuestionIndex <= 0"
        >
          上一题
        </el-button>
        <el-button
            type="primary"
            icon="el-icon-arrow-right"
            @click="nextQuestion"
            :disabled="currentQuestionIndex >= currentPaper.questions.length - 1"
        >
          下一题
        </el-button>
        <el-button
            type="success"
            icon="el-icon-check"
            @click="submitPaper"
            style="float: right"
        >
          提交试卷
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ExamCenter',
  data() {
    return {
      showPaperList: true,
      paperList: [],
      currentPaper: {},
      userAnswers: {},
      currentQuestionIndex: 0, // 当前题号索引
      // 题型名称映射
      questionTypeMap: {
        1: '单选题',
        2: '多选题',
        3: '判断题',
        4: '填空题',
        5: '简答题'
      },
      startTime: null, // 开始时间
      endTime: null, // 结束时间
      totalTime: 30 * 60, // 总时长(秒)，默认30分钟
      remainingTime: 30 * 60, // 剩余时间(秒)
      timer: null // 计时器
    };
  },
  created() {
    this.fetchPaperList();
  },
  mounted() {
    // 监听页面关闭，保存答案
    window.addEventListener('beforeunload', this.saveAnswers);
  },beforeDestroy() {
    // 清除计时器
    if (this.timer) {
      clearInterval(this.timer);
    }
    window.removeEventListener('beforeunload', this.saveAnswers);
  },
  methods: {
    // 获取试卷列表
    async fetchPaperList() {
      try {
        const res = await axios.get('/api/getExamPapers');
        if (res.data.code === 200) {
          this.paperList = res.data.data;
        } else {
          this.$message.error('获取试卷列表失败');
        }
      } catch (error) {
        this.$message.error('网络异常，获取试卷列表失败');
      }
    },

    // 进入试卷详情
    async handlePaperClick(row) {
      try {
        this.currentPaper = this.paperList.find(paper => paper.id === row.id);
        console.log(this.currentPaper)
        this.showPaperList = false;
        this.currentQuestionIndex = 0;
        this.initUserAnswers();
        this.startExam(); // 开始考试计时
      } catch (error) {
        this.$message.error('网络异常，获取试卷详情失败');
      }
    },
    // 开始考试计时
    startExam() {
      this.startTime = new Date();
      this.endTime = new Date(this.startTime.getTime() + this.totalTime * 1000);
      this.remainingTime = this.totalTime;

      // 显示开始时间
      console.log('考试开始时间:', this.startTime.toLocaleString());

      // 启动倒计时
      this.timer = setInterval(() => {
        this.remainingTime--;
        if (this.remainingTime <= 0) {
          this.autoSubmit(); // 时间到自动提交
        }
      }, 1000);
    },
    // 自动提交试卷
    autoSubmit() {
      clearInterval(this.timer);
      this.$message.warning('考试时间到，正在自动提交试卷...');
      this.doSubmit();
    },

    // 初始化答题数据
    initUserAnswers() {
      this.userAnswers = {};
      this.currentPaper.questions.forEach(question => {
        switch(question.type) {
          case 1: // 单选
          case 3: // 判断
          case 4: // 填空
          case 5: // 简答
            this.$set(this.userAnswers, question.id, '');
            break;
          case 2: // 多选
            this.$set(this.userAnswers, question.id, []);
            break;
          default:
            this.$set(this.userAnswers, question.id, '');
        }
      });
    },
    // 格式化时间显示
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },

    // 获取题型名称
    getQuestionTypeName(type) {
      return this.questionTypeMap[type] || '未知题型';
    },

    // 检查题目是否已作答
    isAnswered(questionId) {
      const answer = this.userAnswers[questionId];
      if (typeof answer === 'string') {
        return answer.trim() !== '';
      } else if (Array.isArray(answer)) {
        return answer.length > 0;
      }
      return false;
    },

    // 滚动到指定题目
    scrollToQuestion(index) {
      this.currentQuestionIndex = index;
      const questionEl = this.$refs['questionRef' + index][0];
      if (questionEl) {
        questionEl.scrollIntoView({ behavior: 'smooth' });
      }
    },

    // 上一题
    prevQuestion() {
      if (this.currentQuestionIndex > 0) {
        this.scrollToQuestion(this.currentQuestionIndex - 1);
      }
    },

    // 下一题
    nextQuestion() {
      if (this.currentQuestionIndex < this.currentPaper.questions.length - 1) {
        this.scrollToQuestion(this.currentQuestionIndex + 1);
      }
    },

    // 重置答案
    resetAnswers() {
      this.$confirm('确定要重置所有答案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.initUserAnswers();
        this.$message.success('已重置所有答案');
      });
    },

    // 提交试卷
    async submitPaper() {
      // 检查是否所有题目都已作答
      const allAnswered = this.currentPaper.questions.every(question =>
          this.isAnswered(question.id)
      );

      if (!allAnswered) {
        this.$confirm('还有未完成的题目，确定要提交吗？', '提示', {
          confirmButtonText: '确定提交',
          cancelButtonText: '继续答题',
          type: 'warning'
        }).then(async () => {
          await this.doSubmit();
        });
      } else {
        await this.doSubmit();
      }
    },

    // 执行提交逻辑
    async doSubmit() {
      try {
        const submitData = {
          paperId: this.currentPaper.id,//试卷 ID
          userId: localStorage.getItem('uid'),
          answers: this.userAnswers, // 答案
          startTime: this.startTime.toISOString(), // 开始时间
          endTime: new Date().toISOString() // 提交时间
        };
        const res = await axios.post('/api/submit', submitData);
        if (res.data.code === 200) {
          // this.$message.success('提交成功，你的得分：' + res.data.data.score);
          this.$message.success('提交成功');
          this.showPaperList = true;
        } else {
          this.$message.error('提交失败' );
        }
      } catch (error) {
        this.$message.error('网络异常，提交失败');
      }
    }
  }
};
</script>

<style scoped>
.exam-paper-container {
  padding: 20px;
}
.paper-list-card {
  margin-bottom: 20px;
}
.paper-detail-card {
  min-height: 500px;
}
.question-nav {
  margin-bottom: 20px;
  padding: 10px 0;
}
.question-item {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #ebeef5;
}
.question-title {
  font-weight: bold;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}
.question-type-tag {
  margin-left: 10px;
  font-size: 12px;
  padding: 2px 6px;
  background-color: #f0f2f5;
  border-radius: 4px;
  color: #606266;
}
.question-content {
  padding-left: 20px;
}
.submit-area {
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>